import MVTImageryProvider from 'mvt-imagery-provider'
import { MVTImageryProvider as MVTImageryProviderOnSected } from 'cesium-mvt-imagery-provider'
import mapConfig from '../../mapConfig'
import { mouseLeftClick } from '../../utils/handler'
import { arrayRemoveSame } from '../../utils/tools'

const addMVTImageryData = async (viewer, opts = {}) => {
  const geoserverStyle = {
    version: 8,
    name: 'mapbox-style',
    sources: {
      maplibre: {
        type: 'vector',
        // 'scheme': 'tms',
        tiles: [
          opts.url
          // 'https://demotiles.maplibre.org/tiles/{z}/{x}/{y}.pbf'
          // 'https://iland.zoomlion.com/vectorTile/v2/vectorTiles/polygon_layer/{z}/{x}/{y}?orgId=47035753446400'
          // 'https://iland.zoomlion.com/vectorTile/v2/vectorTiles/polygon_layer/{z}/{x}/{y}?orgId=47035753446400'
        ],
        maxzoom: 22,
        minzoom: 12
      }
    },
    // "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
    // glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
    glyphs: '/cesium-map/font/{fontstack}/{range}.pbf',
    layers: [
      {
        id: 'polygon_fill',
        type: 'fill',
        paint: {
          'fill-outline-color': mapConfig.sectionColor.defaultLineColor,
          'fill-antialias': true,
          'fill-color': mapConfig.sectionColor.defaultColor
        },
        filter: ['all'],
        layout: {
          visibility: 'visible'
        },
        source: 'maplibre',
        maxzoom: 24,
        'source-layer': opts.layer
      }
    ]
  }
  const label = {
    id: 'polygon-label',
    type: 'symbol',
    paint: {
      'text-opacity': {
        stops: [
          [12, 0], // 缩放级别7及以下，文本完全透明（隐藏）
          [16, 1] // 缩放级别9及以上，文本完全不透明（可见）
        ]
      },
      // 文本的颜色
      'text-color': mapConfig.sectionColor.textColor
    },
    filter: ['all'],
    layout: {
      // 文本的字体集合
      'text-font': ['Open Sans Semibold'],
      // 文本的大小
      'text-size': {
        stops: [
          [12, 6], // 缩放级别9，文本大小10px
          [16, 18] // 缩放级别16，文本大小20px
        ]
      },
      // 'text-size': [
      //   'interpolate',
      //   ['linear'],
      //   ['zoom'],
      //   12, // 最小缩放级别
      //   6, // 对应文本大小
      //   16, // 最大缩放级别
      //   16 // 对应文本大小
      // ],
      // 文本所对应的字段
      'text-field': '{name}',
      // 'text-field': {
      //   stops: [
      //     [2, '{name}'],
      //     [4, '{name}'],
      //     [6, '{name}']
      //   ]
      // },
      visibility: 'visible',
      // 文本的最大宽度，超过则折行
      'text-max-width': 10
      // 文本大小写转换
      // 'text-transform': {
      //   stops: [
      //     [0, 'uppercase'],
      //     [2, 'none']
      //   ]
      // }
    },
    source: 'maplibre',
    maxzoom: 24,
    minzoom: 0,
    'source-layer': opts.layer
  }
  const isLabel = opts.isLabel || (opts.isLabel === undefined && true) // 是否隐藏地图标注，true默认显示，false隐藏标注
  if (isLabel) {
    geoserverStyle.layers.push(label)
  }
  // const imageryProvider = new MVTImageryProvider({
  // 已废弃
  //   style: geoserverStyle
  // })
  const imageryProvider = await MVTImageryProvider.fromUrl(geoserverStyle)
  // 注册cesium点击事件，获取切片原始数据的信息
  mouseLeftClick(viewer, onClick => {
    const pickRay = viewer.camera.getPickRay(onClick.position)
    const featuresPromise = viewer.imageryLayers.pickImageryLayerFeatures(
      pickRay,
      viewer.scene
    )
    Promise.resolve(featuresPromise).then(features => {
      // This function is called asynchronously when the list if picked features is available.
      console.log(`Number of features: ${features.length}`)
      if (features.length > 0) {
        console.log(`First feature name: ${features[0].name}`)
        console.log(`features: `, features, features[0].data[features[0].name])
        const data = features[0].data[features[0].name]
        const result = arrayRemoveSame(data, 'id')
        console.log('result', result)
      }
    })
  })
  return viewer.imageryLayers.addImageryProvider(imageryProvider)
}

const addMVTOnSelected = (viewer, opts = {}) => {
  /**
   * 加载mvt切片数据
   */
  const imageryProvider = new MVTImageryProviderOnSected({
    urlTemplate: opts.url,
    layerName: opts.layer, // or "layerName1,layerName2,layerName3"
    style: _feature => {
      // console.log(_feature)
      return {
        strokeStyle: mapConfig.sectionColor.defaultLineColor,
        fillStyle: mapConfig.sectionColor.defaultColor,
        lineWidth: 1
      }
    },
    onSelectFeature: _feature => {
      console.log('Feature is selected', _feature)
    },
    credit: 'cesium.js'
  })
  viewer.imageryLayers.addImageryProvider(imageryProvider)
  // const layers = viewer.scene.imageryLayers;
  // const currentLayer = layers.addImageryProvider(imageryProvider);
  // currentLayer.alpha = 0.5;
}

export { addMVTImageryData, addMVTOnSelected }
